import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, DatePicker, Empty, Form, Icon, Input, message } from 'antd';
import { useRequest } from '@/hooks';
import useDynamicList from '@/hooks/useDynamicList';
import moment from 'moment';
import FormContainer from './FormContainer';

const RANGE_PICKER_FORMAT_YYYY_MM_DD = 'YYYY-MM-DD';

const formatDate = date => (date ? moment(date).format('YYYY-MM-DD') : '--');
/**
 * 员工档案 - 获奖记录
 */
const AwardRecordSection = ({ formData, onChange, readonly, saveAction, ...props }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 列表管理
    const {
        list: awardList,
        remove: awardListRemove,
        push: awardListPush,
        getKey: awardListGetKey,
        resetList: awardListReset
    } = useDynamicList([]);

    useEffect(() => {
        // 重置列表的值
        awardListReset(formData.awardList);
    }, [awardListReset, formData.awardList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('awardList', { initialValue: formData.awardList || [] });
    }, [formData.awardList]);

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            entryPersonnelCode: formData.entryPersonnelCode,
            newList: awardList.map((item, index) => {
                const key = awardListGetKey(index);
                return {
                    awardTime: values.awardTime[key] ? values.awardTime[key]?.format('YYYY-MM-DD') : null,
                    awardName: values.awardName[key] ? values.awardName[key] : null,
                    organize: values.organize[key] ? values.organize[key] : null
                };
            })
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData.newList);
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        awardListReset(formData.awardList);
    };

    // 取消编辑
    const handleEdit = () => {
        if (awardList.length === 0) {
            awardListPush({});
        }
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="获奖记录"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
            {...props}
        >
            {({ getFieldDecorator }, editStatus) => (
                <div className="dynamicList">
                    {awardList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    <div className="dynamicListContainer">
                        {awardList.map((item, index) => (
                            <div key={awardListGetKey(index)} className="dynamicListItem">
                                {editStatus && props.isEntryGuide && (
                                    <div className="dynamicListItemHeader">获奖记录 {index + 1}</div>
                                )}
                                {editStatus && (
                                    <Icon
                                        onClick={() => awardListRemove(index)}
                                        className="dynamicListClose"
                                        type="close-circle"
                                        theme="filled"
                                    />
                                )}
                                <Form.Item label="获奖时间">
                                    {editStatus
                                        ? getFieldDecorator(`awardTime[${awardListGetKey(index)}]`, {
                                              initialValue:
                                                  item?.awardTime !== '' && item?.awardTime
                                                      ? moment(item?.awardTime)
                                                      : undefined
                                          })(
                                              <DatePicker
                                                  format={RANGE_PICKER_FORMAT_YYYY_MM_DD}
                                                  style={{ width: '100%' }}
                                              />
                                          )
                                        : formatDate(item?.awardTime)}
                                </Form.Item>
                                <Form.Item label="颁发机构">
                                    {editStatus ? (
                                        getFieldDecorator(`organize[${awardListGetKey(index)}]`, {
                                            initialValue: item?.organize ?? undefined,
                                            rules: [{ max: 50, message: '字数不能超过50个字符' }]
                                        })(<Input maxLength={50} placeholder="请输入颁发机构" />)
                                    ) : (
                                        <div className="multiLineText">{item?.organize || '--'}</div>
                                    )}
                                </Form.Item>
                                <Form.Item label="奖项名称">
                                    {editStatus ? (
                                        getFieldDecorator(`awardName[${awardListGetKey(index)}]`, {
                                            initialValue: item?.awardName ?? undefined,
                                            rules: [
                                                { required: true, message: '请填写奖项名称' },
                                                { max: 50, message: '字数不能超过50个字符' }
                                            ]
                                        })(<Input maxLength={50} placeholder="请输入奖项名称" />)
                                    ) : (
                                        <span>{item?.awardName || '--'}</span>
                                    )}
                                </Form.Item>
                            </div>
                        ))}
                    </div>
                    {editStatus ? (
                        <Button className="dynamicListAddButton" block onClick={() => awardListPush({})}>
                            +添加获奖记录
                        </Button>
                    ) : null}
                </div>
            )}
        </FormContainer>
    );
};

// prop
AwardRecordSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

AwardRecordSection.defaultProps = {
    readonly: false,
    saveAction: null
};

export default AwardRecordSection;
